package com.adamrocker.android.sharefelica;

import com.adamrocker.android.sharefelica.service.FelicaService;
import com.felicanetworks.mfc.AppInfo;
import com.felicanetworks.mfc.Felica;
import com.felicanetworks.mfc.FelicaEventListener;
import com.felicanetworks.mfc.FelicaException;
import com.felicanetworks.mfc.PushStartBrowserSegment;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * テスト用のActivity。アプリとしてはShareFelicaListを利用。
 * @author adamrocker
 *
 */
public class ShareFelica extends Activity {
    private Button mBtn;
    private TextView mText;

    private OnClickListener mTestBtn = new OnClickListener() {
        public void onClick(View v) {
            handleTest();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mBtn = (Button) findViewById(R.id.test_btn);
        mBtn.setOnClickListener(mTestBtn);
        mText = (TextView) findViewById(R.id.msg_tv);
    }

    public void onResume() {
        super.onResume();
        FelicaService service = FelicaService.getInstance();
        service.setContext(this, new FelicaEventListener() {
            @Override
            public void finished() {
                mBtn.setEnabled(true);
            }

            @Override
            public void errorOccurred(int arg0, String arg1, AppInfo arg2) {
                showMessage("FelicaEventListener#errorOccurred(" + arg0 + ", "
                        + arg1 + ", " + arg2.toString());
            }
        });
        try {
            service.connectAndActivate();
        } catch (Exception e) {
            e.printStackTrace();
            String msg = e.getMessage();
            showMessage(msg);
        }
    }

    public void onPause() {
        super.onPause();
        FelicaService service = FelicaService.getInstance();
        try {
            service.disconnectAndInactivate();
        } catch (Exception e) {
            e.printStackTrace();
            String msg = e.getMessage();
            showMessage(msg);
        }
    }

    public void handleTest() {
        Felica felica = FelicaService.getFelica();
        try {
            felica.open();
            PushStartBrowserSegment pushSegment = new PushStartBrowserSegment(
                    "http://www.google.com", null);
            felica.push(pushSegment);
            felica.close();
        } catch (FelicaException e) {
            e.printStackTrace();
            showMessage("FelicaEventListener.finished.FelicaException:"
                    + e.getID());
        }
    }

    public void showMessage(String msg) {
        // Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
        mText.setText(msg);
    }
}